package com.mathdroid.gui.main.browser;

import java.awt.Color;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;

import javax.swing.JTextField;
import javax.swing.event.DocumentEvent;
import javax.swing.event.DocumentListener;

import com.mathdroid.model.Model;

/**
 * This Listener can be used as both MouseListener and DocumentListener for
 * SearchFields. Note that you can't modify the text of the TextField from 
 * inside of this listener, because it is mutable locked.
 */
public final class SearchFieldListener 
implements MouseListener, DocumentListener, KeyListener {
	
	/**
	 * The parent TextField component.
	 */
	private JTextField searchField = null;
	
	/**
	 * Create a new Listener.
	 * @param f Parent JTextField.
	 */
	public SearchFieldListener(final JTextField f) {
		this.searchField = f;
	}

	@Override
	public void mouseClicked(final MouseEvent e) {
		this.searchField.selectAll();
	}

	@Override
	public void mouseEntered(final MouseEvent e) { }

	@Override
	public void mouseExited(final MouseEvent e) { }

	@Override
	public void mousePressed(final MouseEvent e) { }

	@Override
	public void mouseReleased(final MouseEvent e) { }

	@Override
	public void changedUpdate(final DocumentEvent e) {
		this.textChanged();
	}

	@Override
	public void insertUpdate(final DocumentEvent e) {
		this.textChanged();	
	}

	@Override
	public void removeUpdate(final DocumentEvent e) {
		this.textChanged();
	}
	
	/**
	 * The text in the JTextField changed and the item browser filter has to
	 * refresh.
	 */
	private void textChanged() {
		this.searchField.setForeground(Color.BLACK);
		Model.getProfile().getItemBrowserModel().setRegExFilter(
				this.searchField.getText());
	}

	@Override
	public void keyPressed(final KeyEvent e) {
		if (e.getKeyCode() == KeyEvent.VK_ENTER) {
			Model.getProfile().getItemBrowserModel().setRegExFilter(
					this.searchField.getText());
		}
	}

	@Override
	public void keyReleased(final KeyEvent e) { }

	@Override
	public void keyTyped(final KeyEvent e) { }
}
